package com.woniuxy.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.HospitalMeta;
import com.woniuxy.mapper.HospitalMapper;
import com.woniuxy.service.IHospitalService;
import com.woniuxy.util.InitDBUtil;
import com.woniuxy.util.PageParam;
import com.woniuxy.util.ResponseData;
import com.woniuxy.util.ResponseEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author：xurice
 * @date：Created in 2024/4/21 13:47
 * @description：
 * @modified By：
 * @version: $
 */
@Service
public class HospitalServiceImpl implements IHospitalService {
    @Autowired
    HospitalMapper hospitalMapper;
    @Override
    public List<HospitalMeta> selectAvailable(HospitalMeta hospitalMeta) {
        return hospitalMapper.selectAvailable(hospitalMeta);
    }

    @Override
    public ResponseData<?> addHospital(HospitalMeta hospitalMeta) {
        if (StringUtils.isEmpty(hospitalMeta.getHospitalName()) || StringUtils.isEmpty(hospitalMeta.getHospitalAddress())) {
            return new ResponseData<>().fail(ResponseEnum.EMPTY);
        }
        hospitalMapper.addHospital(hospitalMeta);
        return new ResponseData<>().ok();
    }

    @Override
    public ResponseData<?> queryHospital(PageParam<HospitalMeta> pageParam) {
        HospitalMeta hospitalMeta = pageParam.getParam();
        PageHelper.startPage(pageParam.getPageNum(),pageParam.getPageSize());
        List<HospitalMeta> hospitalMetas = hospitalMapper.selectHospital(hospitalMeta);
        PageInfo<HospitalMeta> pageInfo = new PageInfo<>(hospitalMetas);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public ResponseData<?> addDB(HospitalMeta hospitalMeta) {
        List<HospitalMeta> hospitalMetas = hospitalMapper.selectAvailable(hospitalMeta);
        if (hospitalMetas!=null) {
            for (HospitalMeta meta : hospitalMetas) {
                if (meta.getMysqlSchema().equals(hospitalMeta.getMysqlSchema())) {
                    return new ResponseData<>().fail(ResponseEnum.SCHEMA_REPEAT);
                }
            }
        }
        boolean b = InitDBUtil.initDB(hospitalMeta.getMysqlUrl(), hospitalMeta.getMysqlSchema(), hospitalMeta.getMysqlUsername(), hospitalMeta.getMysqlPassword());
        if (!b){
            return new ResponseData<>().fail(ResponseEnum.FAIL);
        }
        hospitalMapper.updateHospital(hospitalMeta);
        return new ResponseData<>().ok();
    }

}
